import json

import numpy as np
import pandas as pd

from datareport.api import ImageUtil
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style

@style()
class GuanMoQingKuang_GaiLan_27(BaseParagraph):
    """
    观摩情况
    """

    def __init__(self):
        super().__init__()
        self.text = '''{}年，累计{}个党支部的组织生活接受观摩，覆盖率达{}%;累计{}人参加组织生活观摩（累计{}场次）,覆盖率达{}%。'''
        self.sort = 18
        self.section = 5

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        df=pd.read_sql('''
        select * from t_meetingplan where isObserve=1
        ''',con=conn)
        count=len(df)
        percent=round(100*df['isObserve'].mean(),1)
        person_num=pd.read_sql('''select count(distinct code) from t_observerenroll where year(createTime)={}'''.format(year),con=conn)
        changci=pd.read_sql('''select concat(month(createTime),'月') month from t_observerenroll where year(createTime)={}'''.format(year),con=conn)
        changci['month']=changci['month'].astype(str)
        all_person_df=pd.read_sql('''select observer from t_observer where completeStatus=\'通过\' and year(createTime)={}'''.format(year),con=conn)
        all_person=0
        for i in np.arange(len(all_person_df)):
            obstr=all_person_df.iloc[i].at['observer']
            jsonob=json.loads(obstr)
            all_person+=len(jsonob)
        self.text=self.text.format(year,count,percent,person_num.values[0][0],len(changci),round(100*person_num.values[0][0]/all_person,1))
        mons_df=changci['month'].value_counts().reset_index(drop=False)
        img=ImageUtil.plot(mons_df,ylable='场次')
        self.image=img

